package org.dormi.learn.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @author : dormi330
 * @since : 22/04/18
 */
public class CompletableFutureDemo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long t1 = System.currentTimeMillis();

        CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (Exception e) {

                }
                return "hello";
            }
        });

        // Block and wait for the future to complete
        // String unused = future.get();

        CompletableFuture<String> f2 = future.thenApply(x -> x + ",world");
        System.out.println("f2=" + f2.get()); // hello,world

        CompletableFuture<Integer> f3 = f2.thenApply(x -> x.length());
        System.out.println("f3=" + f3.get());

        System.out.println("time cost=" + (System.currentTimeMillis() - t1));
    }
}
